<?
/**
 * HttpClient 클래스 
 * 
 * @package php.net 
 */

/**
 * HttpClient 클래스 정의 
 * 
 * 
 * @package php.net
 * 
 */
class HttpClient extends PObject {

	private $header = array();
	private $host;
	private $data;
	private $uri;

	private $con;
	private $result;

	public function __construct($host) {
		$this->host = $host;
	}

	public function setHeader($list) { 
		foreach ($list as $key => $value) { 
			$this->addHeader($key, $value);
		}
	}

	public function addHeader($key, $value) {
		$this->uri[strtoupper($key)] = $value;
	}

	public function connect() { 
        $this->con = fsockopen($this->host, 80, $errno, $errstr, 30);
//		echo "aa";
		if (!$this->con) { 
            echo "$errstr ($errno)<br/>\n";
            echo $da;
			exit;
		}
	}

	public function close() { 
		fclose($this->con);
	}

	public function doHEAD($uri, $header = array(), $data) { 
		$temp = $this->createHttpMessage("HEAD", $uri, $header, $data) ; 

		$data = $this->getData($temp);

		return $data;

	}

	public function doPost($uri, $header = array(), $data) { 
		$temp = $this->createHttpMessage("POST", $uri, $header, $data) ; 

		$data = $this->getData($temp);

		return $data;

	}

	public function doGet($uri, $header = array(), $data) { 
		$temp = $this->createHttpMessage("GET", $uri, $header, $data) ; 

		$data = $this->getData($temp);

		return $data;
	}

	private function createHttpMessage($method, $uri, $header, $data) { 
		$method = strtoupper($method);

		if (in_array($method, array('GET','HEAD'))) { 
			$uri = "{$uri}?$data";
		}

		$temp = "";
        $temp .= "{$method} {$uri}  HTTP/1.1\r\n";
		$temp .= "Host: {$this->host}\r\n";
		$temp .= "User-Agent: EasyLogic Client \r\n";

		if ($method == 'POST') { 
			$temp .= "Content-Type: application/x-www-form-urlencoded\r\n";
			$temp .= "Content-Length: ".strlen($data)."\r\n";
		}
		$temp .= "Connection: close\r\n\r\n";

		if ($method == 'POST') { 
			$temp .= $data;
		}

		return $temp;
	}

	public function getData($msg) { 
		$temp = "";

		fputs($this->con, $msg);

		while(!feof($this->con)) { 
			$temp .= fread($this->con, 4096);;	
		}

		$arr = explode("\r\n\r\n", $temp);

		$header = array_shift($arr);
		$body	= implode("\r\n\r\n", $arr);

		return array(
			'header' => $header,
			'body'	 => $body
		);
	}
}

?>